import Request from './request'
import { VUE_APP_BASE_URL_PREFIX, TIME_OUT, TOKEN } from '@/constants'
import { useStorage, useStorageType } from '@/utils/useStorage'

const fetch = new Request({
  baseURL: VUE_APP_BASE_URL_PREFIX,
  timeout: TIME_OUT,
  // 是否允许发送Cookie 如果为true 则服务器的 Access-control-Allow-Credentials 必须为 true 来源为 XMLHttpRequest的withCredentials配置项
  withCredentials: true,
  interceptorHooks: {
    requestInterceptor: (config) => {
      const token = useStorage.getItem(TOKEN, useStorageType.Cookies)
      if (token) {
        if (config && config.headers) {
          // config.headers.Authorization = `Bearer ${token}`
          config.headers[TOKEN] = token
        }
      }
      return config
    },
    requestInterceptorCatch: (err) => {
      return err
    },
    responseInterceptor: (res) => {
      return res.data
    },
    responseInterceptorCatch: (err) => {
      return err
    }
  }
})

export default fetch
